from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import json
from content.models import UserRating,UserShopping
from .models import User
from .forms import RegisterForm


@csrf_exempt
def login(request):
    if request.method == 'GET':
        return render(request, 'login/login.html')

    data = json.loads(request.body.decode('utf-8'))
    type = data['role']
    print('data:',data)
    # 移除data中的role
    data.pop('role')
    user = User.objects.filter(**data).first()
    if user:
        print('登录成功', user)
        # 设置session
        request.session['user_id'] = user.id
        request.session.set_expiry(0)
        if type == 'admin':
            return HttpResponse('999')
        else:
            return HttpResponse('200')
    return HttpResponse('403')


@csrf_exempt
def register(request):
    if request.method == 'GET':
        form = RegisterForm()
        return render(request, 'login/register.html', {'form': form})

    form = RegisterForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        if data['password'] != data['confirm_password']:
            messages.error(request, '两次密码不一致')
            return render(request, 'login/register.html', {'form': form})
        data.pop('confirm_password')
        User.objects.create(**data)
        messages.success(request, '注册成功')
        return render(request, 'login/register.html', {'form': form})
    return render(request, 'login/register.html', {'form': form})


@csrf_exempt
def exit(request):
    # 清除session
    request.session.clear()
    return render(request, 'login/login.html')

@csrf_exempt
def user_info(request):
    user_id = request.session.get('user_id')
    user= User.objects.filter(id=user_id).first()
    # 获取所有关联数据
    ratings = UserRating.objects.filter(user=user)
    shoppings = UserShopping.objects.filter(user=user)
    rating_his = ''
    shopping_his = ''
    for shopping in shoppings:
        rating_his += shopping.goods.name + '、'
    for rating in ratings:
        shopping_his += rating.goods.name + '、 '

    return render(request, 'login/user_info.html', {'user':user, 'rating_his':rating_his,'shopping_his':shopping_his})
